package com.mangix.http;

import com.mangix.conf.MangixConfig;
import com.mangix.core.MangixNode;
import com.mangix.files.MangixFiles;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;


/**
 * Created by Ahan on 2014/5/12.
 */
public class MangixServer {

    public static final int INIT = 0;
    public static final int START = 1;

    private int state;

    private MangixConfig config;
    private MangixFiles mangixFiles;

    private MangixNode knownNode;
    private MangixNode localNode;

    private String hostname;
    private int port;

    public MangixServer(MangixNode node) {
        this(node, null);
    }

    public MangixServer(MangixNode node, MangixNode knownNode) {
        this.localNode = node;
        this.config = node.getConfig();
        this.mangixFiles = node.getFiles();
        this.hostname = node.getHostName();
        this.port = node.getPort();
        this.knownNode = knownNode;
    }

    public MangixConfig getConfig() {
        return this.config;
    }

    public MangixNode getNode() {
        return localNode;
    }

    public void start() {
//        Thread[] workerThread = new Thread[5];
//        for (Thread t : workerThread) {
//            t = new Thread(new MangixWorker(eventQueue, mangixFiles, config));
//            t.start();
//        }
        Server server = new Server();
//        ServerConnector http = new ServerConnector(server);
        ServerConnector http = new ServerConnector(server);
        http.setHost(hostname);
        http.setPort(port);
        http.setIdleTimeout(30000);
        server.addConnector(http);
        ServletHandler handler = new ServletHandler();
        server.setHandler(handler);
        handler.addServletWithMapping(new ServletHolder(new MangixCommonServlet(this)), "/");
        handler.addServletWithMapping(new ServletHolder(new MangixObjectServlet(this)), "/objects/*");
        handler.addServletWithMapping(new ServletHolder(new MangixDirectObjectServlet(this)), "/direct/objects/*");

        try {
            server.start();
            System.out.println("mangix.Mangix Http Server is running on " + localNode.toString() + ".");
            try {
                if (knownNode == null) {
                    localNode.init();
                } else {
                    localNode.init(knownNode);
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.exit(-1);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }

    }

}

